import axios from 'axios'
import config from './config'
import NProgress from 'nprogress' 
import 'nprogress/nprogress.css'

import qs from 'qs' // 序列化请求数据，视服务端的要求
axios.defaults.withCredentials = true
NProgress.configure({ showSpinner: false })
export default function $axios(options) {
    // Promise 是用来处理异步操作的  Promise有三种状态：pending（进行中），resolved（完成），rejected（失败）
return new Promise((resolve, reject)=>{
  const instance=axios.create({
        baseURL:config.baseURL,
        headers:{},
        transformResponse:[data => {
        }]
    })

// request 拦截器
instance.interceptors.request.use(
  config => {
    NProgress.start()
    if (config.method === 'post') {
      if (config.data.__proto__ === FormData.prototype
        || config.url.endsWith('path')
        || config.url.endsWith('mark')
        || config.url.endsWith('patchs')
      ) {
      } else {
        config.data = qs.stringify(config.data)
      }
    }
    return config
  },
  error => {
    return Promise.reject(error) 
  }
)
 // response 拦截器
instance.interceptors.response.use(
  response => {
    NProgress.done()
    let data;
    // IE9时response.data是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
    if (response.data == undefined) {
      data = JSON.parse(response.request.responseText)
    } else {
      data = response.data
    }
    return data
},err=>{
  NProgress.done()
    if (err && err.response) {
        switch (err.response.status) {
          case 400:
            err.message = '请求错误'
            break

          case 401:
            err.message = '未授权，请登录'
            break

          case 403:
            err.message = '拒绝访问'
            break

          case 404:
            err.message = `请求地址出错: ${err.response.config.url}`
            break

          case 408:
            err.message = '请求超时'
            break

          case 500:
            err.message = '服务器内部错误'
            break

          case 501:
            err.message = '服务未实现'
            break

          case 502:
            err.message = '网关错误'
            break

          case 503:
            err.message = '服务不可用'
            break

          case 504:
            err.message = '网关超时'
            break

          case 505:
            err.message = 'HTTP版本不受支持'
            break

          default:
        }
      }
      console.error(err)
      return Promise.reject(err) // 返回接口返回的错误信息
}
)
   // 请求处理
   instance(options).then(res => {
    resolve(res)
    return false
  }).catch(error => {
    reject(error)
  })
})
}
